


import java.io.*;

import java.net.*;



import java.sql.*;


import org.python.util.PythonInterpreter;

import com.hogofwar.DJbot.BasePlugin;
import com.hogofwar.DJbot.IRCBase;

public class COM_log implements BasePlugin {

	public void start(final IRCBase irc, final String[] extra, String channel,
			String sender, String hostname, boolean usename) {
		// System.out.println(extra[0]);
		// System.out.println(extra[1]);

		String start = "";
		if (usename == true) {
			start = sender + ": ";
		}

		if (extra.length != 0) {
			if (extra[0] != " ") {

				String tosend = null;
				String data2 = null;
				String name = null;
				String fin = "Logs for " + channel + "\n";
				String amount = extra[0];
				int amount2 = 50;
				Boolean cont = false;
				try {
					Integer.parseInt(amount);
					cont = true;
				} catch (Exception e) {
					cont = false;
				}
				if (cont) {
					try {
						Class.forName("org.sqlite.JDBC");
						Connection conn = DriverManager
								.getConnection("jdbc:sqlite:chat.db");
						Statement stat = conn.createStatement();

						ResultSet rs = stat
								.executeQuery("SELECT * FROM ( SELECT * FROM people where channel = '"
										+ channel
										+ "' ORDER BY time DESC LIMIT 1,"
										+ extra[0] + " ) x ORDER BY time ASC");
						while (rs.next()) {
							int hour = rs.getInt("hour");
							String hour2 = Integer.toString(hour);
							int minute = rs.getInt("minute");
							String minute2 = Integer.toString(minute);
							int second = rs.getInt("seconds");
							String second2 = Integer.toString(second);
							if (hour < 10) {
								hour2 = "0" + hour;
								// hour = Integer.parseInt(hour2);
							}
							if (minute < 10) {
								minute2 = "0" + minute;
								// minute = Integer.parseInt(minute2);
							}
							if (second < 10) {
								second2 = "0" + second;
								// second = Integer.parseInt(second2);
							}
							String status = "";
							if (rs.getString("status") == null) {
								status = "";
							} else {
								status = rs.getString("status");
							}
							if (rs.getString("name").equalsIgnoreCase("*")) {
								fin = fin + "\n[" + hour2 + ":" + minute2 + ":"
										+ second2 + "] " + rs.getString("name")
										+ " " + rs.getString("message");
							} else {
								fin = fin + "\n[" + hour2 + ":" + minute2 + ":"
										+ second2 + "] <" + status + ""
										+ rs.getString("name") + "> "
										+ rs.getString("message");
							}
						}
					} catch (ClassNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					// Construct data
					PythonInterpreter interp = new PythonInterpreter();
					Writer out = new StringWriter();
					interp.setOut(out);
					if (extra.length > 1) {

						if (extra[1].equalsIgnoreCase("pastebin")
								|| extra[1].equalsIgnoreCase("pb")) {
							try {
								String data = URLEncoder.encode("api_option",
										"UTF-8")
										+ "="
										+ URLEncoder.encode("paste", "UTF-8");
								data += "&"
										+ URLEncoder.encode(
												"api_paste_private", "UTF-8")
										+ "=" + URLEncoder.encode("0", "UTF-8");
								data += "&"
										+ URLEncoder.encode("api_paste_name",
												"UTF-8")
										+ "="
										+ URLEncoder.encode("LOG for "
												+ channel, "UTF-8");
								// data += "&" +
								// URLEncoder.encode("api_paste_expire_date",
								// "UTF-8") + "=" + URLEncoder.encode("",
								// "UTF-8");
								data += "&"
										+ URLEncoder.encode("api_paste_format",
												"UTF-8") + "="
										+ URLEncoder.encode("text", "UTF-8");
								data += "&"
										+ URLEncoder.encode("api_dev_key",
												"UTF-8")
										+ "="
										+ URLEncoder
												.encode("e09fc1cd4fa34259d92240bb957baf62",
														"UTF-8");
								data += "&"
										+ URLEncoder.encode("api_paste_code",
												"UTF-8") + "="
										+ URLEncoder.encode(fin, "UTF-8");
								// Send data
								URL url = new URL(
										"http://pastebin.com/api/api_post.php");
								URLConnection conn2 = url.openConnection();
								conn2.setDoOutput(true);
								OutputStreamWriter wr = new OutputStreamWriter(
										conn2.getOutputStream());
								wr.write(data);
								wr.flush();

								// Get the response
								BufferedReader rd = new BufferedReader(
										new InputStreamReader(
												conn2.getInputStream()));
								String line;
								while ((line = rd.readLine()) != null) {
									// Process line...
									System.out.println(line);
									tosend = "The logs you requested are here: "
											+ line;
								}
								wr.close();
								rd.close();
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else if (extra[1].equalsIgnoreCase("pastie")) {

							interp.set("text", fin);
							interp.set("syntax", "plain_text");
							interp.exec("import urlparse,urllib2,re,sys,urllib");
							interp.exec("data = {'paste[parser]': syntax,'paste[body]': text.encode('utf8'),'paste[authorization]': 'burger','paste[restricted': '1'}");
							interp.exec("print urllib2.urlopen(\"http://www.pastie.org/pastes\", urllib.urlencode(data)).url");

							String result = out.toString();
							tosend = "The logs you requested are here: "
									+ result;

						} else if (extra[1].equalsIgnoreCase("gist")
								|| extra[1].equalsIgnoreCase("git")) {
							interp.set("text", fin);
							interp.set("description", "LOG for " + channel);
							interp.set("syntax", "");
							interp.exec("import urlparse,urllib2,re,sys,urllib");
							interp.exec("data = { 'file_contents[gistfile1]': text.encode('utf8'),  'action_button': \"private\" }");
							interp.exec("if description: data['description'] = description");
							interp.exec("req = urllib2.urlopen('https://gist.github.com/gists', urllib.urlencode(data).encode('utf8'))");
							interp.exec("print req.url");
							String result = out.toString();
							tosend = "The logs you requested are here: "
									+ result;
						} else if (extra[1].equalsIgnoreCase("ubuntu")
								|| extra[1].equalsIgnoreCase("ub")) {
							interp.set("text", fin);
							interp.set("user", "None");
							interp.set("syntax", "text");
							interp.exec("import urlparse,urllib2,re,sys,urllib");

							interp.exec("data = urllib.urlencode({\"poster\": user, \"syntax\": syntax, \"content\":text.encode('utf8')})");
							interp.exec("print urllib2.urlopen(\"http://paste.ubuntu.com/\", data).url");
							String result = out.toString();
							tosend = "The logs you requested are here: "
									+ result;
						}
					} else {

						interp.set("text", fin);
						// interp.set("nyud", ".nyud.net");
						interp.set("syntax", "n");
						interp.exec("import urlparse,urllib2,re,sys,urllib");
						interp.exec("data = urllib.urlencode({\"sprunge\":text.encode('utf8')})");
						interp.exec("url = urllib2.urlopen(\"http://sprunge.us/\", data).read().strip()");
						interp.exec("if syntax: url += \"?\"+syntax");
						interp.exec("print url");
						// interp.exec("print re.search(r'var url = \\'([^\\']+)\\'', urllib2.urlopen(url).read()).group(1)");
						String result = out.toString();
						tosend = "The logs you requested are here: " + result;
					}

					// address.getCanonicalHostName()
					// tosend = " seems to be up.";

					
					irc.sendMessage(channel, start + "" + tosend);
				} else {
					irc.sendMessage(channel, start + "Not a valid input!");
				}
			} else {
			
				irc.sendMessage(channel, start + "You need to specify a number!");
			}
		} else {
			
			irc.sendMessage(channel, start + "You need to specify a number!");
		}
	}

	public String help() {
		return "Log - log ((optional)PasteBin)[amount] - Gets the logs and posts them on pastebin with the specified amount of messages.";
		// TODO Auto-generated method stub

	}

	// public static boolean exists(String URLName){
	// try {
	// HttpURLConnection.setFollowRedirects(true);
	// // note : you may also need
	// //HttpURLConnection.setInstanceFollowRedirects(false)
	// HttpURLConnection con =
	// (HttpURLConnection) new URL(URLName).openConnection();
	// con.setRequestMethod("HEAD");
	// return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
	// }
	// catch (Exception e) {
	// e.printStackTrace();
	// return false;
	// }
	// }
	public String version() {
		return "Haspaid version 1";
		// TODO Auto-generated method stub

	}

	@Override
	public String restrict() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Boolean hide() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String aliases() {
		// TODO Auto-generated method stub
		return "getlog, logget, pastelog, loget";
	}

}
